package com.yonsz.cloud.open.platform.moduels.client.controller;


import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yonsz.cloud.open.platform.model.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Value("${server.url.prefix}")
    private String serverUrlPrefix;
    @Value("${security.auth.server}")
    private String authServerUrl;
    @Value("${web.url.prefix}")
    private String webServerUrl;
    @Value("${test.clientId}")
    String clientId = "xxx";
    @Value("${test.clientSecret}")
    String clientSecret = "xxx";

    /**
     * 授权登录，不绑定家庭
     * /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String callbackUrl = getRedirectUrl(true);
        String redirect = authServerUrl + "/oauth/authorize?appId=0000&response_type=code&client_id=" + clientId + "&state=xyz&redirect_uri=" + callbackUrl;
        response.sendRedirect(redirect);
    }

    /**
     * 授权登录（先绑定家庭）
     * /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/login2", method = RequestMethod.GET)
    public void login2(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String appId = "1103"; //安顺祥智控用户
        String appId2 = "1101"; //语音遥控器用户
        String callbackUrl = getRedirectUrl(true);
        String redirect = webServerUrl + "/box/proxy/authorize/" + clientId + "/"+appId+"/?response_type=code&client_id=" + clientId + "&state=xyz&redirect_uri=" + callbackUrl;
        response.sendRedirect(redirect);
    }

    protected String getRedirectUrl(boolean urlEncoding) throws UnsupportedEncodingException {
        String callbackUrl = serverUrlPrefix + "/test/callback";
        if (urlEncoding) {
            callbackUrl = URLEncoder.encode(callbackUrl, StandardCharsets.UTF_8.name());
        }
        return callbackUrl;
    }

    /**
     * 授权回调获取token
     *
     * @param request
     * @param code
     * @param state
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/callback", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult callback(HttpServletRequest request, @RequestParam String code, @RequestParam String state) throws UnsupportedEncodingException {
        // grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
        //&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
        //向授权服务器获取token
        String callbackUrl = getRedirectUrl(false);
        String send = authServerUrl + "/oauth/token";
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        params.put("redirect_uri", callbackUrl);
        params.put("client_id", clientId);
        params.put("client_secret", clientSecret);
        String res = HttpUtil.post(send, params);
        return ApiResult.success("获取token成功", JSONUtil.parse(res));
    }

}
